package com.xywh.wanandroid.compose_ui.main

import android.app.Activity
import androidx.activity.OnBackPressedCallback
import androidx.activity.compose.LocalOnBackPressedDispatcherOwner
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.PagerState
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.material3.DrawerState
import androidx.compose.material3.DrawerValue
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ModalNavigationDrawer
import androidx.compose.material3.Scaffold
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.rememberDrawerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.platform.LocalContext
import androidx.hilt.navigation.compose.hiltViewModel
import com.xywh.wanandroid.compose_ui.main.bottomBar.HomeScreen
import com.xywh.wanandroid.compose_ui.main.bottomBar.ProjectScreen
import com.xywh.wanandroid.compose_ui.main.bottomBar.SquareScreen
import com.xywh.wanandroid.compose_ui.main.bottomBar.SystemScreen
import com.xywh.wanandroid.compose_ui.main.bottomBar.WechatScreen
import com.xywh.wanandroid.data.model.bean.KnowledgeTreeItem
import com.xywh.wanandroid.ext.showToastMsg
import com.xywh.wanandroid.viewmodel.MainComposeViewModel
import kotlinx.coroutines.CoroutineScope


@OptIn(ExperimentalFoundationApi::class, ExperimentalMaterial3Api::class)
@Composable
fun MainScreen(
    mainComposeViewModel: MainComposeViewModel = hiltViewModel(),
    modifier: Modifier = Modifier,
    navigateRank: () -> Unit,
    navigateLogin: () -> Unit,
    navigateScore: () -> Unit,
    navigateCollect: () -> Unit,
    navigateSearch: () -> Unit,
    navigateWebView: (String, String) -> Unit,
    navigateKnowledge: (String, KnowledgeTreeItem) -> Unit
) {
    val activity = LocalContext.current as Activity

    val drawerState: DrawerState = rememberDrawerState(DrawerValue.Closed)
    val pageState = rememberPagerState(pageCount = { 5 })
    val coroutineScope = rememberCoroutineScope()
    val scrollBehavior = TopAppBarDefaults.enterAlwaysScrollBehavior()


    ModalNavigationDrawer(
        drawerState = drawerState,
        drawerContent = {
            MainDrawerContent(
                mainComposeViewModel,
                navigateRank = navigateRank,
                navigateLogin = navigateLogin,
                navigateScore = navigateScore,
                navigateCollect = navigateCollect
            )
        }
    ) {

        Scaffold(
            modifier = modifier.nestedScroll(scrollBehavior.nestedScrollConnection),

            topBar = {

                MainTopBar(
                    pageState,
                    coroutineScope,
                    drawerState,
                    scrollBehavior = scrollBehavior
                ) {
                    navigateSearch.invoke()
                }
            },

            bottomBar = {
                MainBottomBar(pageState, coroutineScope)
            }
        ) { innerPadding ->


            MainContent(
                pageState,
                mainComposeViewModel,
                innerPadding,
                coroutineScope,
                navigateWebView = navigateWebView,
                navigateKnowledge = navigateKnowledge
            )


        }

    }


    val callback = remember {
        var exitTime = 0L
        object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                if (System.currentTimeMillis() - exitTime > 2000) {
                    showToastMsg("再按一次退出程序")
                    exitTime = System.currentTimeMillis()
                } else {
                    activity.finish()
                }
            }
        }
    }
    val dispatcher = LocalOnBackPressedDispatcherOwner.current?.onBackPressedDispatcher
    DisposableEffect(key1 = Unit, effect = {
        dispatcher?.addCallback(callback)
        onDispose {
            callback.remove()
        }
    })
}

@Composable
@OptIn(ExperimentalFoundationApi::class)
private fun MainContent(
    pageState: PagerState,
    mainComposeViewModel: MainComposeViewModel,
    innerPadding: PaddingValues,
    scope: CoroutineScope,
    navigateKnowledge: (String, KnowledgeTreeItem) -> Unit,
    navigateWebView: (String, String) -> Unit,

    ) {


    HorizontalPager(
        state = pageState,
        Modifier.padding(innerPadding)
    ) { index ->

        when (index) {
            0 -> {
                HomeScreen(mainComposeViewModel, innerPadding, navigateWebView)
            }

            1 -> {
                SquareScreen(mainComposeViewModel, innerPadding, navigateWebView)
            }

            2 -> {
                WechatScreen(mainComposeViewModel, innerPadding, navigateWebView)
            }

            3 -> {
                SystemScreen(
                    innerPadding,
                    mainComposeViewModel,
                    scope,
                    navigateWebView,
                    navigateKnowledge
                )
            }

            4 -> {
                ProjectScreen(mainComposeViewModel, innerPadding, navigateWebView)
            }
        }
    }
}

fun cancelOrAddCollectArticle(
    collect: Boolean,
    mainComposeViewModel: MainComposeViewModel,
    id: Int
) {
    if (collect) {
        mainComposeViewModel.cancelCollectArticle(id)
    } else {
        mainComposeViewModel.addCollectArticle(id)
    }
}

